import {
	defineStore
} from 'pinia';

export const useTextLayoutStore = defineStore('textLayout', {
	state: () => ({
		// 布局样式
		fontSize: 16, //字体大小
		lineHeight: 1, //行高
		marginHorizontal: 16, //水平间距
		marginVertical: 16, //上下间距
		lineSpace: 20, //行间距
		// 屏幕信息
		screenWidth: 0,
		screenHeight: 0,
		
		//文字范围
		availableWidth:0,
		availableHeight:0,
		
		// 分页信息
		charsPerLine: 0,
		linesPerPage: 0,
		charsPerPage: 0,
		currentPage: 1,
		totalPages: 1,

		// 内容管理
		fullText: '',
		pages: [],
		pageCache: new Map(),

		// 章节信息
		bookName: '',
		chapters: [],
		currentChapter: 0,

		// 加载状态
		loading: false,
		loadingProgress: 0,
		error: null
	}),

	getters: {
		readingProgress: (state) => {
			return ((state.currentPage - 1) / Math.max(state.totalPages - 1, 1) * 100).toFixed(2);
		},

		currentChapterInfo: (state) => {
			return state.chapters[state.currentChapter] || null;
		},

		isReady: (state) => {
			return !state.loading && state.pages.length > 0;
		}
	},

	actions: {
		// 初始化布局
		async initLayout() {
			try {
				const systemInfo = uni.getSystemInfoSync();
				this.screenWidth = systemInfo.windowWidth;
				this.screenHeight = systemInfo.windowHeight;
				await this.calculateLayout();
			} catch (error) {
				console.error('初始化布局失败:', error);
				throw error;
			}
		},

		// 计算布局参数
		async calculateLayout() {
			try {

				// 设计计算
				this.availableWidth = this.screenWidth - (this.marginHorizontal * 2);
				this.availableHeight = this.screenHeight - (this.marginVertical * 2) - 30 - 28 - 10;

				this.charsPerLine = Math.floor(this.availableWidth / this.fontSize);
				
				this.linesPerPage = Math.floor(this.availableHeight / (this.fontSize * this.lineHeight));
				this.charsPerPage = this.charsPerLine * this.linesPerPage;
				
				if (this.fullText) {
					await this.paginateText();
				}
			} catch (error) {
				console.error('计算布局失败:', error);
				throw error;
			}
		},

		// 加载本地文件
		async loadLocalFile(filePath) {
			try {
				this.loading = true;
				this.loadingProgress = 0;
				this.error = null;

				// 尝试从缓存加载
				const cacheKey = `novel_${filePath.split('/').pop()}`;
				const cachedData = uni.getStorageSync(cacheKey);

				if (cachedData?.version === '1.0' && cachedData.data) {
					await this.loadFromCache(cachedData.data);
				} else {
					const content = await this.readFileContent(filePath);
					await this.processContent(content, filePath);
				}

				this.loading = false;
				this.loadingProgress = 100;
			} catch (error) {
				this.loading = false;
				this.error = error.message;
				console.error('加载文件失败:', error);
				throw error;
			}
		},

		// 读取文件内容
		async readFileContent(filePath) {
			return new Promise((resolve, reject) => {
				plus.io.resolveLocalFileSystemURL(filePath, (entry) => {
					entry.file((file) => {
						const reader = new plus.io.FileReader();

						reader.onload = (e) => {
							this.loadingProgress = 30;
							resolve(e.target.result);
						};

						reader.onerror = (e) => {
							reject(new Error('读取文件失败'));
						};

						reader.readAsText(file, 'UTF-8');
					});
				}, (error) => {
					reject(new Error('无法访问文件'));
				});
			});
		},

		// 从缓存加载
		async loadFromCache(cachedData) {
			this.fullText = cachedData.fullText;
			this.pages = cachedData.pages;
			this.chapters = cachedData.chapters;
			this.bookName = cachedData.bookName;
			this.totalPages = cachedData.pages.length;
			this.currentPage = 1;
			this.currentChapter = 0;
			this.loadingProgress = 100;

			// 重新计算布局
			await this.calculateLayout();
		},

		// 处理文本内容
		async processContent(content, filePath = '') {
			if (!content) {
				throw new Error('文本内容为空');
			}

			this.fullText = content;
			this.loadingProgress = 40;

			// 解析章节
			await this.parseChapters();
			this.loadingProgress = 60;

			// 分页处理
			await this.paginateText();
			this.loadingProgress = 90;

			// 保存缓存
			if (filePath) {
				const cacheKey = `novel_${filePath.split('/').pop()}`;
				const cacheData = {
					version: '1.0',
					data: {
						fullText: this.fullText,
						pages: this.pages,
						chapters: this.chapters,
						bookName: this.bookName,
					}
				};

				try {
					uni.setStorageSync(cacheKey, cacheData);
				} catch (error) {
					console.error('保存缓存失败:', error);
				}
			}
		},

		// 解析章节
		async parseChapters() {
			const chapterRegex = /第[一二三四五六七八九十百千万\d]+章[^\n]*/g;
			const matches = [...this.fullText.matchAll(chapterRegex)];

			this.chapters = matches.map((match, index) => {
				const startIndex = match.index;
				const endIndex = index < matches.length - 1 ? matches[index + 1].index : this
					.fullText.length;
				const title = match[0].slice(0, 10);
				return {
					title,
					startIndex,
					endIndex,
					startPage: 0,
					endPage: 0
				};
			});

			// // 设置书名
			this.bookName = this.chapters[0]?.title.split('第')[0] || '未知书名';
		},

		// 文本分页
		/**
		 * 异步将完整文本分页处理，避免阻塞主线程
		 * 处理逻辑：
		 * 1. 根据预设的每页行数和每行字符数进行分页
		 * 2. 优先保留完整的行（以\n为界）
		 * 3. 每处理50页暂停一次，让出主线程控制权
		 */
		async paginateText() {
			// 边界检查：如果没有文本内容或每页字符数为0，则直接返回
			if (!this.fullText || this.charsPerPage === 0) return;

			// 重置分页结果和缓存
			this.pages = [];
			this.pageCache.clear();

			const totalLength = this.fullText.length;
			let currentIndex = 0; // 当前处理到的文本位置
			
			// 主循环：按页处理文本
			while (currentIndex < totalLength) {
				let pageContent = ''; // 当前页的文本内容
				let lineCount = 0; // 当前页的行数计数器
				
				// 子循环：处理当前页的每一行
				while (lineCount < this.linesPerPage && currentIndex < totalLength) {
					// 查找下一个换行符的位置
					const nextNewlineIndex = this.fullText.indexOf('\n', currentIndex);
					
					// 计算当前行应该截取的长度
					let lineLength = this.charsPerLine;
					if (nextNewlineIndex !== -1 && nextNewlineIndex - currentIndex < this.charsPerLine) {
						// 如果换行符在当前行长度内，截取到换行符
						lineLength = nextNewlineIndex - currentIndex + 1;
					}
					
					// 截取当前行文本
					const lineText = this.fullText.slice(currentIndex, currentIndex + lineLength);
					pageContent += lineText;
					
					// 移动指针到下一行开始位置
					currentIndex += lineLength;
					
					// 如果是换行符结尾，跳过额外的换行符
					if (lineText.endsWith('\n')) {
						currentIndex++; // 跳过换行符
					}
					
					lineCount++;
				}
				
				// 将当前页添加到分页结果数组
				this.pages.push(pageContent);
				
				// 异步优化：每处理50页让出主线程，避免长时间阻塞UI
				if (this.pages.length % 50 === 0) {
					await new Promise(resolve => setTimeout(resolve, 0));
				}
			}

			// 更新分页元数据
			this.totalPages = this.pages.length;
			this.currentPage = Math.min(this.currentPage, this.totalPages);

			// 触发章节页面更新
			await this.updateChapterPages();
		},

		// 更新章节页码
		async updateChapterPages() {
			let currentPage = 1;
			let currentLength = 0;

			for (const chapter of this.chapters) {
				// 找到章节开始页
				while (currentLength < chapter.startIndex && currentPage <= this.totalPages) {
					currentLength += (this.pages[currentPage - 1] || '').length;
					currentPage++;
				}
				chapter.startPage = currentPage;

				// 找到章节结束页
				while (currentLength < chapter.endIndex && currentPage <= this.totalPages) {
					currentLength += (this.pages[currentPage - 1] || '').length;
					currentPage++;
				}
				chapter.endPage = currentPage - 1;
			}
		},

		// 获取当前页内容
		getCurrentPageContent() {
			const pageIndex = this.currentPage - 1;

			if (this.pageCache.has(pageIndex)) {
				return this.pageCache.get(pageIndex);
			}

			const content = this.pages[pageIndex] || '';
			this.pageCache.set(pageIndex, content);
			// console.log(content);
			return content;
		},
		

		// 翻页控制
		nextPage() {
			if (this.currentPage < this.totalPages) {
				this.currentPage++;
				this.updateCurrentChapter();
			}
		},

		previousPage() {
			if (this.currentPage > 1) {
				this.currentPage--;
				this.updateCurrentChapter();
			}
		},

		// 更新当前章节
		updateCurrentChapter() {
			for (let i = 0; i < this.chapters.length; i++) {
				const chapter = this.chapters[i];
				if (this.currentPage >= chapter.startPage &&
					(i === this.chapters.length - 1 || this.currentPage < this.chapters[i + 1].startPage)) {
					this.currentChapter = i;
					break;
				}
			}
		},

		// 跳转到指定章节
		jumpToChapter(chapterIndex) {
			if (chapterIndex >= 0 && chapterIndex < this.chapters.length) {
				this.currentPage = this.chapters[chapterIndex].startPage;
				this.currentChapter = chapterIndex;
			}
		},

		// 更新字体大小
		async updateFontSize(size) {
			this.fontSize = size;
			await this.calculateLayout();
		},

		// 重置状态
		reset() {
			this.fullText = '';
			this.pages = [];
			this.chapters = [];
			this.currentPage = 1;
			this.totalPages = 1;
			this.currentChapter = 0;
			this.loadingProgress = 0;
		},

		// 加载文本内容
		async loadTextContent(content) {
			try {
				this.loading = true;
				this.loadingProgress = 0;
				this.error = null;

				await this.processContent(content);

				this.loading = false;
				this.loadingProgress = 100;
			} catch (error) {
				this.loading = false;
				this.error = error.message;
				console.error('加载文本内容失败:', error);
				throw error;
			}
		},

		// 加载文本文件
		async loadTextFile(filePath) {
			try {
				await this.loadLocalFile(filePath);
			} catch (error) {
				console.error('加载文本文件失败:', error);
				throw error;
			}
		}
	}
});